/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
/*
 * This copy of Woodstox XML processor is licensed under the
 * Apache (Software) License, version 2.0 ("the License").
 * See the License for details about distribution rights, and the
 * specific rights regarding derivate works.
 *
 * You may obtain a copy of the License at:
 *
 * http://www.apache.org/licenses/
 *
 * A copy is also included in the downloadable source code package
 * containing Woodstox, in file "ASL2.0", under the same directory
 * as this file.
 */
package com.je.bpm.engine.impl.cmd;

import com.alibaba.fastjson2.JSONObject;
import com.je.bpm.common.operation.OperatorEnum;
import com.je.bpm.core.model.BpmnModel;
import com.je.bpm.core.model.button.factory.ButtonEnum;
import com.je.bpm.core.model.config.CustomEvent;
import com.je.bpm.engine.ActivitiTaskAlreadyClaimedException;
import com.je.bpm.engine.delegate.DelegateHelper;
import com.je.bpm.engine.impl.bpmn.behavior.KaiteBaseUserTaskActivityBehavior;
import com.je.bpm.engine.impl.interceptor.CommandContext;
import com.je.bpm.engine.impl.persistence.entity.TaskEntity;
import com.je.bpm.engine.upcoming.ActivitiUpcomingRun;
import com.je.bpm.engine.upcoming.UpcomingCommentInfoDTO;

import java.util.Map;

/**
 * 声明任务命令
 */
public class ClaimTaskCmd extends NeedsActiveTaskCmd<Void> {

    private static final long serialVersionUID = 1L;

    protected String userId;

    public ClaimTaskCmd(String taskId, String prod, Map<String, Object> bean, String userId) {
        super(taskId, prod, bean);
        this.userId = userId;
    }

    @Override
    protected Void execute(CommandContext commandContext, TaskEntity task) {
        if (userId != null) {
            task.setClaimTime(commandContext.getProcessEngineConfiguration().getClock().getCurrentTime());
            if (task.getAssignee() != null) {
                if (!task.getAssignee().equals(userId)) {
                    // When the task is already claimed by another user, throw
                    // exception. Otherwise, ignore
                    // this, post-conditions of method already met.
                    throw new ActivitiTaskAlreadyClaimedException(task.getId(), task.getAssignee());
                }
            } else {
                UpcomingCommentInfoDTO upcomingInfo = DelegateHelper.buildUpcomingInfo(null, "", SubmitTypeEnum.RECEIVE,
                        task.getBusinessKey(), task.getId(), null);
                ActivitiUpcomingRun activitiUpcomingRun = commandContext.getProcessEngineConfiguration().getActivitiUpcomingRun();
                activitiUpcomingRun.completeUpcoming(upcomingInfo);
                commandContext.getTaskEntityManager().changeTaskAssignee(task, userId);
            }
        } else {
            // Task claim time should be null
            task.setClaimTime(null);

            // Task should be assigned to no one
            commandContext.getTaskEntityManager().changeTaskAssignee(task, null);
        }

        JSONObject taskConfigs = JSONObject.parseObject(String.valueOf(task.getVariable(KaiteBaseUserTaskActivityBehavior.TASK_GLOBAL_VAR)));
        JSONObject form = taskConfigs.getJSONObject(KaiteBaseUserTaskActivityBehavior.FORM_VAR_NAME);
        JSONObject buttons = form.getJSONObject(KaiteBaseUserTaskActivityBehavior.BUTTON_VAR_NAME);
        String current = buttons.getString(KaiteBaseUserTaskActivityBehavior.CURRENT);
        current = current.replace(ButtonEnum.RECEIVE_BTN.getCode(), ButtonEnum.SUBMIT_BTN.getCode());
        buttons.put(KaiteBaseUserTaskActivityBehavior.CURRENT, current);
        task.setVariable(KaiteBaseUserTaskActivityBehavior.TASK_GLOBAL_VAR, taskConfigs);

        // Add claim time to historic task instance
        commandContext.getHistoryManager().recordTaskClaim(task);

        BpmnModel bpmnModel = commandContext.getProcessEngineConfiguration().getRepositoryService().getBpmnModel(task.getProcessDefinitionId());

        executeAfterHandler(bpmnModel, task, CustomEvent.CustomEventEnum.TASK_RECEIVE, "领取", OperatorEnum.TASK_CLAIM_OPERATOR, "");

        return null;
    }

    @Override
    protected String getSuspendedTaskException() {
        return "Cannot claim a suspended task";
    }

}
